package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.config.RedisProperties;
import cn.itcast.consumer.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @Autowired
    private RedisProperties redisProperties;

    @GetMapping("redis")
    public RedisProperties redisProperties() {
        return redisProperties;
    }

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id, HttpServletRequest request) {
        String truth = request.getHeader("truth");
        System.out.println("truth = " + truth);
        return userClient.findById(id);
    }

    /*
    @Autowired
    private RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "queryByIdFallback", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
    })
    @GetMapping("{id}")
    public String queryById(@PathVariable("id") Long id) {
        // 人为控制成功或失败，触发熔断
        if(id == 1){
            throw new RuntimeException("我是故意的！");
        }
        // 准备URL
        String url = "http://user-service/user/" + id;
        // 远程调用
        return restTemplate.getForObject(url, String.class);
    }*/

    public String queryByIdFallback(Long id) {
        return "别挤了，服务器快炸了！";
    }


    /*
    @Autowired
    private DiscoveryClient discoveryClient;

    int i = 0;
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id) {
        // 从注册中心，动态拉取服务
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 负载均衡，从实例列表中，挑选一个
        // int index = new Random().nextInt(instances.size());
        // i = (i + 1) % instances.size();
        ServiceInstance instance = instances.get(i);
        String host = instance.getHost();
        int port = instance.getPort();
        // 准备URL
        String url = String.format("http://%s:%d/user/%d", host, port, id);
        // 远程调用
        return restTemplate.getForObject(url, User.class);
    }*/
}
